﻿// Jinx AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core.Parsing.ContextFree
{
    public sealed class Grammar
    {
        public static Grammar<S> New<S>(Nonterminal<S> StartSymbol)
        {
            return new Grammar<S>(StartSymbol);
        }
    }

    public class Grammar<S>
    {
        public Grammar(Nonterminal<S> StartSymbol)
        {
            this.StartSymbol = StartSymbol;

            Nonterminals = Graph.Reachable<INonterminal>(StartSymbol, Ss => from P in Ss.Productions
                                                                            from S in P.Symbols
                                                                            where S is INonterminal
                                                                            select S as INonterminal);

            Nonterminals = Series.New(Nonterminals);

            Terminals = from N in Nonterminals
                        from P in N.Productions
                        from S in P.Symbols
                        where S is ITerminal
                        select S as ITerminal;

            Terminals = Series.New(Terminals);

            Symbols = Nonterminals.Cast<ISymbol>().Union(Terminals.Cast<ISymbol>());
        }

        public Nonterminal<S> StartSymbol { get; private set; }
        public IEnumerable<INonterminal> Nonterminals { get; private set; }
        public IEnumerable<ITerminal> Terminals { get; private set; }
        public IEnumerable<ISymbol> Symbols { get; private set; }

        public override string ToString()
        {
            var buffer = new StringBuilder();

            foreach (var N in Nonterminals)
            {
                buffer.AppendFormat("{0} -> ", N.Name);

                var First = true;
                foreach (var P in N.Productions)
                {
                    if (!First)
                        buffer.Append("| ");

                    foreach (var S in P.Symbols)
                        buffer.AppendFormat("{0} ", S.Name);

                    First = false;
                }

                buffer.AppendLine();
            }

            return buffer.ToString();
        }
    }
}